package com.jianzh5.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jianzh5.common.DataPage;
import com.jianzh5.common.DataTables;
import com.jianzh5.dao.BaseDaoI;
import com.jianzh5.entity.TCategory;
import com.jianzh5.entity.TProduct;
import com.jianzh5.page.PageUtil;
import com.jianzh5.page.PageView;
import com.jianzh5.pojo.PAdmin;
import com.jianzh5.pojo.PProduct;
import com.jianzh5.service.ProductServiceI;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by jianzh5 on 2016/11/24.
 */
@Service("productService")
public class ProductServiceImpl implements ProductServiceI{

    private final Logger logger = Logger.getLogger(ProductServiceImpl.class);

    @Autowired
    private BaseDaoI<TProduct> productDao;

    @Autowired
    private BaseDaoI<TCategory> categoryDao;

    @Override
    public DataTables dataTables(String order, String sort, DataPage dataPage) {
        String hql = "from TProduct t left join fetch t.category c";
        String totalHql = "select count(*) from TProduct t";
        hql += " order by t."+sort+" "+order;
        List<TProduct> tlist = productDao.findByPosition(hql, dataPage.getStart(), dataPage.getLength());


        List<PProduct> plist = Lists.newArrayList();
        for(TProduct t : tlist){
            PProduct p = new PProduct();
            BeanUtils.copyProperties(t, p);

            p.setCid(t.getCategory().getId());
            p.setCname(t.getCategory().getName());

            plist.add(p);
        }
        long records = productDao.count(totalHql);
        DataTables dt = new DataTables();
        dt.setDraw(dataPage.getDraw());
        dt.setRecordsTotal(records);
        dt.setRecordsFiltered(records);
        dt.setData(plist);
        return dt;
    }

    @Override
    public List<TCategory> productCategory() {
        String hql = "from TCategory t";
        List<TCategory> tlist = categoryDao.find(hql);
        return tlist;
    }

    @Override
    public PProduct getProduct(int id) {
        TProduct t = productDao.get(TProduct.class,id);
        PProduct p = new PProduct();
        if(t != null){
            BeanUtils.copyProperties(t,p);
            p.setCid(t.getCategory().getId());
            p.setCname(t.getCategory().getName());
            return p;
        }
        return null;
    }

    @Override
    public void updateProduct(PProduct product, PAdmin pAdmin) {
        if(product.getCid() == 0){
            product.setCid(1);
        }
        TCategory category = categoryDao.get(TCategory.class,product.getCid());
        if(product.getId() == 0){  //添加
            TProduct t = new TProduct();
            BeanUtils.copyProperties(product,t);
            t.setCreateDate(new Date());
            t.setCategory(category);
            t.setCreateUser(pAdmin.getUsername());
            productDao.save(t);
        }else{
            TProduct t = productDao.get(TProduct.class,product.getId());
            t.setCategory(category);
            BeanUtils.copyProperties(product,t,new String[]{"createDate","createUser"});
        }
    }

    @Override
    public void delProduct(int gid, HttpServletRequest request) {
        TProduct t = productDao.get(TProduct.class,gid);
        String logoFile = t.getFilepath();
        if (StringUtils.isNotEmpty(logoFile)) {
            String realPath = request.getSession().getServletContext().getRealPath(logoFile);
            FileUtils.deleteQuietly(new File(realPath));
        }
        productDao.delete(t);

    }


    /**
     * 首页获取指定的查询数据
     * @param page
     * @param cid 产品类别
     * @return
     */
    @Override
    public PageView<PProduct> productList(PageView<PProduct> page,Integer cid,String sort) {
        if(sort == null || sort.equals("")){
            sort = "createDate desc";
        }
        String hql = "from TProduct t left join fetch t.category c where 1=1";
        String totalHql = "select count(*) from TProduct t where 1=1";
        Map<String,Object> params = Maps.newHashMap();
        if(cid != null){
            params.put("cid",cid);
            hql += " and c.id = :cid";
            totalHql += " and t.category.id = :cid";
        }

        hql += " order by t."+sort;
        int total = (int)productDao.count(totalHql,params);
        page = PageUtil.createPage(page,total);
        List<TProduct> tlist = productDao.find(hql, params,page.getCpage(), page.getSize());
        List<PProduct> plist = Lists.newArrayList();
        for(TProduct t : tlist){
            PProduct p = new PProduct();
            BeanUtils.copyProperties(t,p);
            plist.add(p);
        }
        page.setRecords(plist);
        return page;
    }

    @Override
    public List<PProduct> getProductList(int start,int end,String sort) {
        String hql = "from TProduct t order by t."+sort;
        List<TProduct> tlist = productDao.findByPosition(hql, start, end);
        List<PProduct> plist = Lists.newArrayList();
        for(TProduct t : tlist){
            PProduct p = new PProduct();
            BeanUtils.copyProperties(t,p);
            plist.add(p);
        }
        return plist;
    }


}
